import requests
from bs4 import BeautifulSoup

import matplotlib.pyplot as plt
import tkinter as tk
from tkinter import ttk, messagebox
import random

# 模拟爬取胜负彩数据函数（实际需替换为真实爬取逻辑，这里根据图片构造模拟数据）
def crawl_lottery_data():
    # 构造模拟的比赛数据，实际应从目标网站爬取，这里仅示例
    match_data = [
        {"league": "欧冠", "time": "8-13 00:00", "home": "卡拉巴", "draw": "平局", "away": "斯肯迪", "odds_home": 1.38, "odds_draw": 4.79, "odds_away": 8.72},
        {"league": "欧冠", "time": "8-13 1:00", "home": "哥本哈", "draw": "平局", "away": "马尔默", "odds_home": 1.72, "odds_draw": 3.49, "odds_away": 4.93},
        {"league": "欧冠", "time": "8-13 1:00", "home": "费内巴", "draw": "平局", "away": "费耶诺", "odds_home": 1.83, "odds_draw": 3.80, "odds_away": 3.87},
        {"league": "欧冠", "time": "8-13 1:00", "home": "比尔森", "draw": "平局", "away": "流浪者", "odds_home": 1.91, "odds_draw": 3.81, "odds_away": 3.71},
        {"league": "欧冠", "time": "8-13 1:30", "home": "布鲁日", "draw": "平局", "away": "萨茨堡", "odds_home": 1.86, "odds_draw": 3.82, "odds_away": 4.12},
        {"league": "欧冠", "time": "8-13 2:15", "home": "费伦茨", "draw": "平局", "away": "卢多戈", "odds_home": 1.91, "odds_draw": 3.30, "odds_away": 3.75},
        {"league": "欧冠", "time": "8-13 2:15", "home": "布拉迪", "draw": "平局", "away": "阿拉木", "odds_home": 1.70, "odds_draw": 3.95, "odds_away": 4.27},
        {"league": "欧冠", "time": "8-13 3:00", "home": "本菲卡", "draw": "平局", "away": "尼斯", "odds_home": 1.68, "odds_draw": 3.90, "odds_away": 5.00},
        {"league": "欧超杯", "time": "8-14 3:00", "home": "日尔曼", "draw": "平局", "away": "热刺", "odds_home": 1.45, "odds_draw": 4.72, "odds_away": 6.04},
        {"league": "欧协联", "time": "8-14 00:00", "home": "伊斯坦", "draw": "平局", "away": "维京", "odds_home": 1.74, "odds_draw": 3.91, "odds_away": 4.03},
        # 可继续补充更多场比赛数据...
    ]
    return match_data

# 计算金额函数（简单示例，根据实际规则调整）
def calculate_amount(selected_matches, mode):
    # 假设单注 2 元，这里根据不同转 9 模式及所选场次等简单计算，实际规则复杂需详细处理
    # 先判断是否选够对应模式需要从多少场里选 9 场
    required_total = {
        10: 10,
        11: 11,
        12: 12,
        13: 13,
        14: 14
    }[mode]
    if len(selected_matches) != 9:
        return 0
    # 假设这里简单按注数 1 计算，实际需考虑复式等情况
    return 2 * 1  # 示例，实际根据规则完善

# 可视化界面类
class LotteryVisualizer:
    def __init__(self, root):
        self.root = root
        self.root.title("胜负彩任9可视化程序")

        self.match_data = crawl_lottery_data()
        self.mode = tk.StringVar(value="14")  # 默认 14 转 9
        self.selected_matches = []

        # 创建控件
        self.create_widgets()

    def create_widgets(self):
        # 模式选择
        mode_frame = ttk.Frame(self.root)
        mode_frame.pack(pady=10)
        modes = ["10", "11", "12", "13", "14"]
        for m in modes:
            ttk.Radiobutton(mode_frame, text=f"{m}转9", variable=self.mode, value=m).pack(side=tk.LEFT, padx=5)

        # 比赛列表展示
        self.tree = ttk.Treeview(self.root, columns=('联赛', '时间', '主队', '平局', '客队', '主胜赔率', '平赔率', '客胜赔率', '选择'),
                                 show='headings', selectmode='extended')
        self.tree.heading('联赛', text='联赛')
        self.tree.heading('时间', text='时间')
        self.tree.heading('主队', text='主队')
        self.tree.heading('平局', text='平局')
        self.tree.heading('客队', text='客队')
        self.tree.heading('主胜赔率', text='主胜赔率')
        self.tree.heading('平赔率', text='平赔率')
        self.tree.heading('客胜赔率', text='客胜赔率')
        self.tree.heading('选择', text='选择')
        self.tree.pack(pady=10)

        # 填充比赛数据
        for idx, match in enumerate(self.match_data):
            self.tree.insert('', 'end', values=(
                match['league'], match['time'], match['home'], match['draw'], match['away'],
                match['odds_home'], match['odds_draw'], match['odds_away'],
                tk.BooleanVar(value=False)  # 用于选择状态
            ))
            # 绑定选择事件
            self.tree.bind('<ButtonRelease-1>', self.on_select)

        # 金额显示标签
        self.amount_label = ttk.Label(self.root, text="金额：0 元")
        self.amount_label.pack(pady=10)

        # 绘图按钮
        ttk.Button(self.root, text="绘制所选比赛赔率图", command=self.plot_odds).pack(pady=5)

    def on_select(self, event):
        selected_items = self.tree.selection()
        current_mode = self.mode.get()
        required_total = int(current_mode)
        for item in selected_items:
            values = self.tree.item(item, 'values')
            match_info = {
                'league': values[0],
                'time': values[1],
                'home': values[2],
                'draw': values[3],
                'away': values[4],
                'odds_home': float(values[5]),
                'odds_draw': float(values[6]),
                'odds_away': float(values[7])
            }
            if match_info not in self.selected_matches:
                self.selected_matches.append(match_info)
        # 限制选择数量为 9 场
        if len(self.selected_matches) > 9:
            self.selected_matches = self.selected_matches[-9:]
        # 计算金额并更新显示
        amount = calculate_amount(self.selected_matches, int(current_mode))
        self.amount_label.config(text=f"金额：{amount} 元")

    def plot_odds(self):
        if len(self.selected_matches) < 9:
            messagebox.showwarning("提示", "请选择至少 9 场比赛")
            return
        home_odds = [m['odds_home'] for m in self.selected_matches]
        draw_odds = [m['odds_draw'] for m in self.selected_matches]
        away_odds = [m['odds_away'] for m in self.selected_matches]
        matches = [f"{m['home']}-{m['away']}" for m in self.selected_matches]

        x = range(len(matches))
        width = 0.25

        fig, ax = plt.subplots()
        ax.bar([i - width for i in x], home_odds, width, label='主胜赔率', color='r')
        ax.bar(x, draw_odds, width, label='平赔率', color='g')
        ax.bar([i + width for i in x], away_odds, width, label='客胜赔率', color='b')

        ax.set_xticks(x)
        ax.set_xticklabels(matches, rotation=45)
        ax.set_xlabel('比赛')
        ax.set_ylabel('赔率')
        ax.legend()
        plt.tight_layout()
        plt.show()

if __name__ == "__main__":
    root = tk.Tk()
    app = LotteryVisualizer(root)
    root.mainloop()